//------------------------------------------------------------------------------
// <copyright company="Telligent Systems">
//     Copyright (c) Telligent Systems Corporation.  All rights reserved.
// </copyright> 
//------------------------------------------------------------------------------

using System;
using System.Collections;
using System.IO;
using System.Web;
using CommunityServer.Components;
using Rss;

namespace CommunityServer.Reader.Components
{
	/// <summary>
	/// Summary description for TreeXML.
	/// </summary>
	public class RollerRssHandler : IHttpHandler
	{
		private int RSSSize;

		#region Constructor(s)
		
		public RollerRssHandler()
		{
			
		}

		#endregion

		#region Public Methods

		public void ProcessRequest(HttpContext context)
		{
			context.Response.ContentType = "text/xml";

			int userId = Users.GetAnonymousUser().UserID;
			CSContext csContext = CSContext.Current;

			ReaderConfiguration config = ReaderConfiguration.Instance(!ReaderConfiguration.Instance().FileOnly);
			RSSSize					   = config.RSSSize;

			FeedPostSet posts = FeedPosts.GetRollerPosts(0,RSSSize);


			RssFeed feed = new RssFeed();
			feed.Version = RssVersion.RSS20;
			RssChannel channel = new RssChannel(csContext.SiteSettings.SiteName, csContext.SiteSettings.SiteDescription, new Uri(csContext.CurrentUri.ToString().Replace("rss.ashx", "default.aspx")));
			for (int i = 0; i < posts.Count; i++)
			{
				FeedPost feedPost = posts[i];
				RssItem item = new RssItem();
				
				item.Author = feedPost.Author;
				item.CommentApiUrl = feedPost.CommentApiUrl;
				item.CommentCount = feedPost.CommentCount;
				item.CommentRss = feedPost.CommentRssUrl;
				item.Comments = feedPost.CommentsUrl;
				item.Creator = feedPost.Creator;
				item.Description = feedPost.Description;

				// Enclosure
				if (feedPost.EnclosureUrl != null && feedPost.EnclosureUrl != "")
				{
					RssEnclosure enclosure = new RssEnclosure();
					enclosure.Length = int.Parse(feedPost.EnclosureLength.ToString());
					enclosure.Type = feedPost.EnclosureType;
					enclosure.Url = new Uri(feedPost.EnclosureUrl);

					item.Enclosure = enclosure;
				}

				// Guid
				RssGuid guid = new RssGuid();
				guid.Name = feedPost.GuidName;
				guid.PermaLink = feedPost.GuidIsPermaLink;

				item.Guid = guid;

				item.Link = new Uri(feedPost.Link);
				item.PubDate = feedPost.PubDate;

				// Source
				if (!Globals.IsNullorEmpty(feedPost.FeedLink))
				{
				
					RssSource source = new RssSource(new Uri(feedPost.FeedLink));
					source.Name = feedPost.FeedTitle;
					item.Source = source;
				}

				if ((feedPost.Title != null) && (feedPost.Title.Trim().Length > 0))
					item.Title = feedPost.Title;
				else
					item.Title = ResourceManager.GetString("roller_feed_no_title", "FeedReader.xml");
				
				channel.Items.Add(item);
			}			
			feed.Channels.Add(channel);

			MemoryStream stream = new MemoryStream();
			if (channel.Items.Count > 0)
				feed.Write(stream);
			else
				WriteEmptyChannelToFeed(stream, feed, channel);	// RSS.NET throws exception if channel is empty
			stream.Position = 0;

			StreamReader reader = new StreamReader(stream);
			
			// Use TreeView's GetXml method to return the XML structure   
			context.Response.Write(reader.ReadToEnd());
		}

		#endregion

		#region Public Properties

		public bool IsReusable
		{
			get { return false; }
		}

		#endregion

		#region Private Helpers
		private void WriteEmptyChannelToFeed(Stream stream, RssFeed feed, RssChannel channel)
		{
			RssWriter writer;

			if (feed.Encoding == null)
				writer = RssWriter.Create(stream, feed.Version);
			else
				writer = RssWriter.Create(stream, feed.Version, feed.Encoding);

			try
			{
				writer.Modules = feed.Modules;
				writer.Write(channel);
			}
			finally
			{
				if (writer != null)
					writer.Close();
			}
		}
		#endregion
	}
}
